<template>
  <div class="vehicle-dispatch">
    <div class="header">
      <router-link to="/main/wuye/vehicle/process" class="back-btn">
        <i class="el-icon-arrow-left"></i>
        <span>返回</span>
      </router-link>
      <h2>车辆派遣</h2>
    </div>

    <div class="content">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="待派遣" name="pending">
          <el-table :data="pendingList" style="width: 100%" v-loading="loading">
            <el-table-column prop="applyNo" label="申请编号" width="180"></el-table-column>
            <el-table-column prop="applicant" label="申请人" width="120"></el-table-column>
            <el-table-column prop="useType" label="用车类型" width="120"></el-table-column>
            <el-table-column prop="useTime" label="用车时间" width="180">
              <template slot-scope="scope">
                {{ formatDateRange(scope.row.useTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="requirements" label="车辆要求" width="150">
              <template slot-scope="scope">
                {{ scope.row.requirements.join('、') }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
                <el-button size="mini" type="primary" @click="handleDispatch(scope.row)">派遣</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="已派遣" name="completed">
          <el-table :data="completedList" style="width: 100%">
            <el-table-column prop="applyNo" label="申请编号" width="180"></el-table-column>
            <el-table-column prop="applicant" label="申请人" width="120"></el-table-column>
            <el-table-column prop="vehicleNo" label="车牌号" width="120"></el-table-column>
            <el-table-column prop="driver" label="司机" width="120"></el-table-column>
            <el-table-column prop="dispatchTime" label="派遣时间" width="180"></el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 详情对话框 -->
    <el-dialog title="用车申请详情" :visible.sync="detailDialogVisible" width="60%">
      <div class="application-detail" v-if="currentApplication">
        <el-descriptions title="申请信息" :column="2" border>
          <el-descriptions-item label="申请编号">{{ currentApplication.applyNo }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentApplication.applicant }}</el-descriptions-item>
          <el-descriptions-item label="用车类型">{{ currentApplication.useType }}</el-descriptions-item>
          <el-descriptions-item label="用车人数">{{ currentApplication.passengerCount }}人</el-descriptions-item>
          <el-descriptions-item label="目的地">{{ currentApplication.destination }}</el-descriptions-item>
          <el-descriptions-item label="预计里程">{{ currentApplication.estimatedMileage }}公里</el-descriptions-item>
        </el-descriptions>

        <div class="detail-section" v-if="currentApplication.dispatchInfo">
          <h4>派遣信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="车牌号">{{ currentApplication.dispatchInfo.vehicleNo }}</el-descriptions-item>
            <el-descriptions-item label="车型">{{ currentApplication.dispatchInfo.vehicleType }}</el-descriptions-item>
            <el-descriptions-item label="司机">{{ currentApplication.dispatchInfo.driver }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentApplication.dispatchInfo.driverPhone }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h4>用车事由</h4>
          <p>{{ currentApplication.reason }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 派遣表单对话框 -->
    <el-dialog title="车辆派遣" :visible.sync="dispatchDialogVisible" width="50%">
      <el-form :model="dispatchForm" label-width="100px">
        <el-form-item label="选择车辆">
          <el-select v-model="dispatchForm.vehicleNo" placeholder="请选择车辆" @change="handleVehicleChange">
            <el-option
              v-for="item in availableVehicles"
              :key="item.vehicleNo"
              :label="`${item.vehicleNo} (${item.vehicleType})`"
              :value="item.vehicleNo">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择司机">
          <el-select v-model="dispatchForm.driver" placeholder="请选择司机">
            <el-option
              v-for="item in availableDrivers"
              :key="item.id"
              :label="`${item.name} (${item.phone})`"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="出发里程">
          <el-input-number v-model="dispatchForm.startMileage" :min="0"></el-input-number>
          <span class="unit">公里</span>
        </el-form-item>

        <el-form-item label="油量">
          <el-input-number v-model="dispatchForm.fuelLevel" :min="0" :max="100"></el-input-number>
          <span class="unit">%</span>
        </el-form-item>

        <el-form-item label="备注说明">
          <el-input type="textarea" v-model="dispatchForm.remark" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dispatchDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDispatch">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 'pending',
      pendingList: [],
      completedList: [],
      detailDialogVisible: false,
      dispatchDialogVisible: false,
      currentApplication: null,
      dispatchForm: {
        vehicleNo: '',
        driver: '',
        startMileage: 0,
        fuelLevel: 100,
        remark: ''
      },
      availableVehicles: [
        { vehicleNo: '粤B12345', vehicleType: '商务车', status: '空闲' },
        { vehicleNo: '粤B67890', vehicleType: '轿车', status: '空闲' }
      ],
      availableDrivers: [
        { id: 1, name: '李四', phone: '13900139000' },
        { id: 2, name: '王五', phone: '13900139001' }
      ],
      loading: false
    }
  },
  methods: {
    formatDateRange(range) {
      if (!range || !Array.isArray(range)) return ''
      return range.map(date => this.formatDate(date)).join(' 至 ')
    },
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleString()
    },
    viewDetail(row) {
      this.currentApplication = row
      this.detailDialogVisible = true
    },
    async handleDispatch(row) {
      try {
        const response = await this.$http.post(`/api/vehicle/dispatch/${row.id}`, this.dispatchForm);
        if (response.code === 200) {
          this.$message.success('派遣成功');
          await this.fetchPendingList();
        } else {
          this.$message.error(response.message || '派遣失败');
        }
      } catch (error) {
        console.error('派遣错误:', error);
        this.$message.error('派遣失败');
      }
    },
    handleVehicleChange(value) {
      const vehicle = this.availableVehicles.find(v => v.vehicleNo === value)
      if (vehicle) {
        this.dispatchForm.vehicleType = vehicle.vehicleType
      }
    },
    submitDispatch() {
      if (!this.dispatchForm.vehicleNo || !this.dispatchForm.driver) {
        this.$message.error('请选择车辆和司机')
        return
      }

      // TODO: 提交派遣信息到后端
      const dispatchInfo = {
        vehicleNo: this.dispatchForm.vehicleNo,
        vehicleType: this.availableVehicles.find(v => v.vehicleNo === this.dispatchForm.vehicleNo).vehicleType,
        driver: this.dispatchForm.driver,
        driverPhone: this.availableDrivers.find(d => d.name === this.dispatchForm.driver).phone,
        startMileage: this.dispatchForm.startMileage,
        fuelLevel: this.dispatchForm.fuelLevel,
        remark: this.dispatchForm.remark
      }

      this.currentApplication.dispatchInfo = dispatchInfo

      // 从待派遣列表移动到已派遣列表
      const index = this.pendingList.findIndex(item => item.applyNo === this.currentApplication.applyNo)
      if (index > -1) {
        const application = { ...this.currentApplication }
        application.vehicleNo = dispatchInfo.vehicleNo
        application.driver = dispatchInfo.driver
        application.dispatchTime = new Date().toLocaleString()
        this.pendingList.splice(index, 1)
        this.completedList.unshift(application)
      }

      this.$message.success('车辆派遣成功')
      this.dispatchDialogVisible = false
    },
    async fetchPendingList() {
      try {
        this.loading = true;
        const response = await this.$http.get('/api/vehicle/pending-dispatch');
        if (response.code === 200) {
          this.pendingList = response.data;
        } else {
          this.$message.error(response.message || '获取待派遣列表失败');
        }
      } catch (error) {
        console.error('获取待派遣列表错误:', error);
        this.$message.error('获取待派遣列表失败');
      } finally {
        this.loading = false;
      }
    }
  },
  created() {
    this.fetchPendingList();
  }
}
</script>

<style lang="scss" scoped>
.vehicle-dispatch {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .detail-section {
    margin-top: 20px;

    h4 {
      margin: 0 0 10px;
      color: #303133;
    }

    p {
      margin: 0;
      color: #606266;
      line-height: 1.6;
    }
  }

  .unit {
    margin-left: 10px;
    color: #606266;
  }
}
</style> 